/*
 *  Player.cpp
 *  MyFirstShooterGame
 *
 *  Created by William on 7/27/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "Player.h"
#include <iostream>

#include "SDL.h"
#include "SDL_image/SDL_image.h"

using namespace std;

Player::Player():
x(240.0f),
y(240.0f),
speed(4.0f),
movingUp(false),
movingDown(false),
movingLeft(false),
movingRight(false),
initialized(false)
{
	ship = IMG_Load("../../images/spaceship.png");
	if (!ship) {
		cout << "Couldn't load ship.png" << endl;
		exit(2);
	}
	cout << "Player image initialized." << endl;
	
//	SDL_SetColorKey(ship, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0);
}

Player::~Player() {
	SDL_FreeSurface(ship);
}

void Player::draw(SDL_Surface *screen) {
	SDL_Rect tempRect;
	SDL_Surface *temp;
	
	if (!initialized) {
		initialized = true;
		temp = SDL_DisplayFormatAlpha(ship);
		SDL_FreeSurface(ship);
		ship = temp;
	}
	
	tempRect.x = static_cast<int> (x);
	tempRect.y = static_cast<int> (y);
	tempRect.w = 64;
	tempRect.h = 64;
	
//	cout << "tempRect [" << tempRect.x << ", " << tempRect.y << "]" << endl;
	
	SDL_BlitSurface(ship, NULL, screen, &tempRect);
}

void Player::tick() {
	if (movingLeft && !movingRight) {
		if (x-speed > 0) {
			updatePosition(x-speed, y);
		}
	}
	else if (movingRight && !movingLeft) {
		if (x+speed < 640 - 32) {
			updatePosition(x+speed, y);
		}
	}
	if (movingUp && !movingDown) {
		if (y-speed > 0) {
			updatePosition(x, y-speed);
		}
	}
	else if (movingDown && !movingUp) {
		if (y+speed < 480 - 32) {
			updatePosition(x, y+speed);
		}
	}

}

void Player::updatePosition(int x, int y) {
	this->x = x;
	this->y = y;
}

void Player::moveLeft(bool val) {
	movingLeft = val;
	
	if (movingLeft) {
		movingRight = false;
	}
}

void Player::moveRight(bool val) {
	movingRight = val;
	
	if (movingRight) {
		movingLeft = false;
	}
}


void Player::moveUp(bool val) {
	movingUp = val;
	
	if (movingUp) {
		movingDown = false;
	}
}

void Player::moveDown(bool val) {
	movingDown = val;
	
	if (movingDown) {
		movingUp = false;
	}
}
